package com.xiao.tripmateai.tools;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import com.xiao.tripmateai.constant.FileConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * PDF 生成工具
 */
@Component
public class PDFGenerationTool {

    @Tool(description = "Generate a PDF file with given content", returnDirect = false)
    public String generatePDF(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Content to be included in the PDF") String content) {

        // 新增：清理JSON非法转义字符 (核心修复)
        String sanitizedContent = cleanJsonEscapes(content);
        String sanitizedFileName = fileName.replaceAll("[<>:\"/\\\\|?*]", "_"); // 清理文件名特殊字符

        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + sanitizedFileName;

        try {
            FileUtil.mkdir(fileDir);
            try (PdfWriter writer = new PdfWriter(filePath);
                 PdfDocument pdf = new PdfDocument(writer);
                 Document document = new Document(pdf)) {

                String fontPath = Paths.get("src/main/resources/static/fonts/simsun.ttf")
                        .toAbsolutePath().toString();
                PdfFont font = PdfFontFactory.createFont(fontPath,
                        PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
                document.setFont(font);

                // 使用清理后的内容
                Paragraph paragraph = new Paragraph(sanitizedContent);
                document.add(paragraph);
            }
            return "PDF generated successfully to: " + filePath;
        } catch (IOException e) {
            return "Error generating PDF: " + e.getMessage();
        }
    }

    // 新增：清理JSON非法转义序列的工具方法
    private String cleanJsonEscapes(String input) {
        if (input == null) return "";

        // 修复非法转义 . 和 / 等问题
        return input.replaceAll("\\\\([^\"\\\\/bfnrtu])", "$1");
    }
}